package com.thm.tfast.modules.sys.controller;


import cn.hutool.http.HttpStatus;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.thm.tfast.core.annotation.Log;
import com.thm.tfast.core.constant.RedisKeyConstant;
import com.thm.tfast.core.entity.ViewResult;
import com.thm.tfast.core.utils.RedisKeyUtil;
import com.thm.tfast.modules.sys.model.SysUser;
import com.thm.tfast.modules.sys.model.dto.user.*;
import com.thm.tfast.modules.sys.model.vo.user.CaptchaVo;
import com.thm.tfast.modules.sys.model.vo.user.UserInfoVo;
import com.thm.tfast.modules.sys.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 用户信息 前端控制器
 * </p>
 *
 * @author THM
 * @since 2022-10-10
 */
@RestController
@Api(tags = "系统：用户管理")
@RequestMapping("/sysUser")
public class SysUserController {
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Resource
    private SysUserService sysUserService;

    @ApiOperation(value = "获取验证码")
    @GetMapping( "/captcha")
    public ViewResult<CaptchaVo> captcha() {
        return ViewResult.success(sysUserService.getCaptcha());
    }

    @ApiOperation(value = "登录以后返回token")
    @PostMapping("/login")
    public ViewResult<Map<String, String>> login(@Validated @RequestBody UserLoginDto dto) {
        String token = sysUserService.login(dto);
        if (token == null) {
            return ViewResult.error(HttpStatus.HTTP_INTERNAL_ERROR,"用户名或密码错误");
        }
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", tokenHead);
        return ViewResult.success(tokenMap);
    }

    @ApiOperation(value = "刷新token")
    @GetMapping( "/refreshToken")
    public ViewResult<Map<String, String>> refreshToken(HttpServletRequest request) {
        String token = request.getHeader(tokenHeader);
        String refreshToken = sysUserService.refreshToken(token);
        if (refreshToken == null) {
            return ViewResult.error("token已经过期！");
        }
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", refreshToken);
        tokenMap.put("tokenHead", tokenHead);
        return ViewResult.success(tokenMap);
    }

    @ApiOperation(value = "获取当前登录用户信息")
    @GetMapping("/info")
    public ViewResult<UserInfoVo> getUserInfo(Principal principal) {
        if(principal==null){
            return ViewResult.error(HttpStatus.HTTP_UNAUTHORIZED,null);
        }
        UserInfoVo userInfo = sysUserService.getUserInfo();
        return ViewResult.success(userInfo);
    }

    @ApiOperation(value = "登出功能")
    @GetMapping( "/logout")
    public ViewResult<String> logout(@RequestParam(value = "username", required = false) String username) {
        sysUserService.logout(username);
        return ViewResult.success();
    }

    @ApiOperation("根据条件分页获取用户列表")
    @GetMapping(value = "/page")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "keyword", value = "关键字：用户名、昵称"),
            @ApiImplicitParam(name = "pageNum", value = "页码", required = true),
            @ApiImplicitParam(name = "pageSize", value = "每页大小", required = true)
    })
    public ViewResult<Page<SysUser>> page(@RequestParam(value = "keyword", required = false) String keyword,
                                          @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                          @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        Page<SysUser> page = sysUserService.page(keyword, pageNum, pageSize);
        return ViewResult.success(page);
    }

    @ApiOperation("获取指定用户信息")
    @GetMapping("/{userId}")
    public ViewResult<SysUser> getUserById(@PathVariable Long userId) {
        SysUser sysUser = sysUserService.getById(userId);
        return ViewResult.success(sysUser);
    }

    @ApiOperation("新增用户信息")
    @PostMapping("/insert")
    public ViewResult<Long> insert(@Validated @RequestBody UserInsertDto dto){
        return ViewResult.success(sysUserService.insert(dto));
    }

    @ApiOperation("修改用户信息")
    @PutMapping("/update")
    public ViewResult<String> update(@Validated @RequestBody UserUpdateDto dto) {
        boolean success = sysUserService.update(dto);
        if (success) {
            return ViewResult.success();
        }
        return ViewResult.error();
    }

    @ApiOperation("禁用或者启用用户")
    @PutMapping("/enableOrDisable/{userId}")
    public ViewResult<String> enableOrDisable(@PathVariable Long userId) {
        boolean success = sysUserService.enableOrDisable(userId);
        if (success) {
            return ViewResult.success();
        }
        return ViewResult.error();
    }

    @ApiOperation("重置用户密码")
    @PutMapping("/reset/password/{userId}")
    public ViewResult<String> resetPassword(@PathVariable Long userId) {
        boolean success = sysUserService.resetPassword(userId);
        if (success) {
            return ViewResult.success();
        }
        return ViewResult.error();
    }

    @ApiOperation("修改密码")
    @PutMapping("/update/password")
    public ViewResult<String> updatePassword(@Validated @RequestBody UserPasswordDto dto) {
        boolean success = sysUserService.updatePassword(dto);
        if (success) {
            return ViewResult.success();
        }
        return ViewResult.error();
    }

    @ApiOperation("删除用户信息")
    @DeleteMapping("/delete/{userId}")
    public ViewResult<String> delete(@PathVariable Long userId){
        boolean success = sysUserService.delete(userId);
        if (success) {
            return ViewResult.success();
        }
        return ViewResult.error();
    }

    @ApiOperation("分配用户角色")
    @PutMapping ("/allot/role")
    public ViewResult<String> allotRole(@Validated @RequestBody UserRoleDto dto){
        boolean success = sysUserService.allotRole(dto);
        if (success) {
            return ViewResult.success();
        }
        return ViewResult.error();
    }



}

